﻿using System;
using br.com.SistemaChamados.Controller;
using br.com.SistemaChamados.Enum;
using br.com.SistemaChamados.Model;
using System.Web.Security;
using br.com.SistemaChamados.Controller.Common;
using br.com.SistemaChamados.Constants;
using br.com.SistemaChamados.Util;
using System.Web.UI.WebControls;

public partial class Pages_PlaceInsert : System.Web.UI.Page
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        ViewStateUserKey = Session.SessionID;
    }

    protected void Page_PreInit(object sender, EventArgs e)
    {
        br.com.SistemaChamados.Model.Common.User loggedUser = new br.com.SistemaChamados.Model.Common.User();
        UserController userController = new UserController();
        if (Session[UserConstants.SESSION_USER_LOGGED_IN] != null)
        {
            loggedUser.Id = Convert.ToInt32(Session[UserConstants.SESSION_USER_LOGGED_IN]);
            loggedUser = userController.GetUser(loggedUser);
            this.MasterPageFile = MasterPageDefiner.defineMasterPageByAccessRole(loggedUser.Profile);
            ((Label)Master.FindControl("lblUser")).Text = loggedUser.Name;
            this.Title = "SysCall - Sistema de chamados [logado como " + loggedUser.Name + "]";
        }
        else
        {
            Response.Redirect("~/Pages/Login/Login.aspx");
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!User.IsInRole("ADMIN"))
        {
            if (!IsPostBack)
            {
                FillDdlState();
            }
        }
        else
        {
            FormsAuthentication.SignOut();
            Response.Clear();
            Response.Redirect("~/Pages/Login/Login.aspx");
        }
    }

    protected void btnInsert_Click(object sender, EventArgs e)
    {
        Place place = new Place();
        PlaceController placeController = new PlaceController();
        City city = null;
        try
        {
            city = createCityToInsert(place, city);
            place.City = city;
            EnumCRUDState resultInsertOperation = placeController.InsetPlace(place);
            if (resultInsertOperation == EnumCRUDState.SQL_SUCCESS)
            {
                Response.Write(@"<script language='javascript'>alert('Local cadastrado com sucesso!');</script>");
                ClearFields();
                ClearDdlCity();
            }
            else
            {
                Response.Write(@"<script language='javascript'>alert('Ocorreu um erro durante o cadastro, por favor tente novamente!');</script>");
            }
        }
        catch (Exception ex)
        {
            Response.Write(@"<script language='javascript'>alert('Ocorreu um erro ao criar o local: <br>" + ex.Message + ".');</script>");
            place = null;
            placeController = null;
        }
    }

    private City createCityToInsert(Place place, City city)
    {
        city = new City();
        city.Id = Convert.ToInt32(ddlCity.SelectedValue);
        place.ZipCode = Convert.ToInt32(txbZip.Text);
        place.Address = Convert.ToString(txbAddress.Text);
        place.Complement = Convert.ToString(txbComplement.Text);
        place.Number = Convert.ToInt32(txbNumber.Text);
        place.City = city;
        place.Description = txbDescription.Text;
        return city;
    }

    private void FillDdlState()
    {
        StateController stateController = new StateController();
        ddlState.DataSource = stateController.GetStates();
        ddlState.DataTextField = "Acronym";
        ddlState.DataValueField = "Id";
        ddlState.DataBind();
        ddlState.Items.Insert(0, "Selecione");
    }

    private void FillDdlCity()
    {
        CityController cityController = new CityController();
        State state = new State();
        if (Convert.ToInt32(ddlState.SelectedIndex) != 0)
        {
            state.Id = Convert.ToInt32(ddlState.SelectedValue);
            ddlCity.DataSource = cityController.listCityByState(state);
            ddlCity.DataTextField = "Description";
            ddlCity.DataValueField = "Id";
            ddlCity.DataBind();
            ddlCity.Items.Insert(0, "Selecione");
        }
        else
        {
            ClearDdlCity();
        }
    }

    private void ClearFields()
    {
        txbAddress.Text = "";
        txbComplement.Text = "";
        txbZip.Text = "";
        txbNumber.Text = "";
        for (int i = 0; i < ddlState.Items.Count; i++)
        {
            ddlState.Items[i].Selected = false;
        }
        ddlState.Items[0].Selected = true;
    }

    private void ClearDdlCity()
    {
        for (int i = 0; i < ddlState.Items.Count; i++)
        {
            ddlState.Items[i].Selected = false;
        }
        ddlState.Items[0].Selected = true;
        ddlCity.DataSource = "";
        ddlCity.DataBind();
    }

    protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
    {
        FillDdlCity();
    }

}